/* eslint-disable @typescript-eslint/no-var-requires */
/* eslint-disable import/no-extraneous-dependencies */
import gulp from 'gulp';
import uglify from 'gulp-uglify-es';
import { createRollupConfig } from './rollup.config';

const clean = require('gulp-clean');
const rollup = require('rollup');
const rollupconfig = require('./rollup.config').default;

gulp.task('clean', () => gulp.src('build', { allowEmpty: true }).pipe(clean()));

gulp.task('buildvue', (cb) => {
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  rollup.rollup(rollupconfig).then(async (rollupOutput: any) => {
    await rollupOutput.write(rollupconfig.output);
    cb();
  });
});

gulp.task('uglify-js', () =>
  gulp.src('./build/**/*.js').pipe(uglify()).pipe(gulp.dest('./build'))
);

gulp.task('buildcss', (cb) => {
  const components = { ...rollupconfig.input };
  // eslint-disable-next-line @typescript-eslint/dot-notation
  delete components['{{ projectName }}'];

  Object.keys(components).forEach((key) => {
    rollup
      .rollup({
        input: components[key],
        ...createRollupConfig(key),
      })
      // eslint-disable-next-line @typescript-eslint/no-explicit-any
      .then(async (rollupOutput: any) => {
        await rollupOutput.write(rollupconfig.output);
        delete components[key];
        if (!Object.keys(components).length) {
          cb();
        }
      });
  });
});

gulp.task('removetmpjs', () =>
  gulp.src('build/index', { allowEmpty: true }).pipe(clean())
);

gulp.task(
  'default',
  gulp.series(['clean', 'buildvue', 'buildcss', 'removetmpjs', 'uglify-js'])
);
